I want to get filtered data from MongoDb using a specific email in my react project. So, I create an HTTP request using an email and then try to use the data, then I get the following error:
GET http://localhost:5000/bloodRequest/amin@gmail.com 404 (Not Found) Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
My client-side requesting code:
useEffect(() => {
fetch(`http://localhost:5000/bloodRequest/amin@gmail.com`)
.then((res) => res.json())
.then((data) => setRequests(data)); }, [requests]);
My server-side code:
app.get("/donateBlood/:email", async (req, res) => {
const email = req.params.email;
const query = { email: email };
const cursor = donateBloodsCollection.find(query);
const result = await cursor.toArray();
res.json(result);
});
But when I change the HTTP request syntax and use the email in the middle of the HTTP link, it works fine. example:
Client-side code:
useEffect(() => {
fetch(`http://localhost:5000/amin@gmail.com/bloodRequest`)
.then((res) => res.json())
.then((data) => setRequests(data)); }, [requests]);
server-side code:
app.get("/:email/donateBlood", async (req, res) => {
const email = req.params.email;
const query = { email: email };
const cursor = donateBloodsCollection.find(query);
const users = await cursor.toArray();
res.json(users);
});
In that case, it works properly, I don't know why? Can you explain, please?
The fetch call is calling a URL /bloodRequest/amin@gmail.com, the corresponding server API definition has /donateBlood/:email, so the 404 error you have got is expected.
GET http://localhost:5000/bloodRequest/amin@gmail.com 404 (Not Found) Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Try either changing the client-side URL to /donateBlood/amin@gmail.com or server-side API to /bloodRequest/:email.
PS: Basically, the code you are trying is syntactically valid. It must have been failed due to typos in the URL or not restarting the server after a particular change. I can see the same URL mismatch in the working code you have posted, so it should also have thrown 404. Please post the exact code you have tried if it doesn't work yet.